var mongoose = require('mongoose');
var fs = require('fs');
var path = require('path')

var schemas = require('../models/models.js')

//get all the project logs saved on the database
exports.getProjectsAll = function(req, res) {
	var newProject = mongoose.model('Project', schemas.ProjectSchema);
	newProject.find({
		type : 'proj'
	}, function(err, found) {
		if(err) {
			console.log(err);
			res.send('Error in getProjectsAll - find');
			return
		}
		res.send(found)
	})
}
//remove a project log from the database
exports.delProjectsAll = function(req, res) {
	var newProject = mongoose.model('Project', schemas.ProjectSchema);
	newProject.find({
		type : 'proj'
	}, function(err, found) {
		for(i in found) {
			found[i].remove()
		}
		res.send('All projects removed')
	})
}
//get the list of projects for the current user with a user query
exports.getProjectsList = function(req, res) {
	var newProject = mongoose.model('Project', schemas.ProjectSchema);
	var user = req.query.user
	var path;
	var files;
	var toSend = "<ul id='example' class='filetree'><li>"
	newProject.find({
		type : 'proj'
	}, function(err, found) {
		for(i in found) {
			if(found[i].users.indexOf(user) != -1) {
				toSend += "<span class='folder'>" + found[i].name + '</span><ul>'
				files = fs.readdirSync(found[i].path)
				for(f in files) {
					toSend += "<li><span class='file' id='" + found[i].path + files[f] + "' onclick='getCode(this.id)'>" + files[f] + "</span></li>"
				}
				toSend += "</ul>"
			}
		}
		toSend += "</li></ul>"
		res.send(toSend)
	})
}

exports.getFileCode = function(req, res) {
	var pathName = req.query.path;
	var name = path.basename(pathName)
	var code = fs.readFileSync(pathName).toString()
	res.send({code: code, fileName : name, path:pathName})

}


exports.saveFile = function (req,res){
	fs.open()
}



